﻿Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.IO
Imports System.Configuration
Imports System.Xml


<System.Web.Services.WebService(Namespace:="http://arma.teamduck.com/armawebservice/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class ArmaWebService
    Inherits System.Web.Services.WebService

    Private ReadOnly key() As Byte = _
{1, 2, 3, 56, 5, 6, 36, 8, 9, 10, 11, 12, 63, 14, 15, 49, 44, 65, 19, 84, 21, 22, 28, 24}
    Private ReadOnly iv() As Byte = {1, 2, 45, 3, 22, 7, 84, 1}

    'Set version for verification with client
    Dim Version As String = "1.3.6.0"

    ' instantiate the class with the arrays
    Private des As New TripleDES(key, iv)

    Private strMissionDirectory As String = ConfigurationSettings.AppSettings("FileSaveToLocation").ToString
    Private strMainDirectory As String = ConfigurationSettings.AppSettings("ArmaLocation").ToString
    Private strTemplateFile As String = ConfigurationSettings.AppSettings("TemplateName").ToString
    Private strConfigFile As String = ConfigurationSettings.AppSettings("ConfigName").ToString
    Private strProfileLocation As String = ConfigurationSettings.AppSettings("ProfileLocation").ToString
    Private strProfileName As String = ConfigurationSettings.AppSettings("ProfileName").ToString
    Private strExeName As String = ConfigurationSettings.AppSettings("ExeName").ToString
    Private strTSExeName As String = ConfigurationSettings.AppSettings("TSExeName").ToString
    Private strTSDirectory As String = ConfigurationSettings.AppSettings("TSLocation").ToString
    Private strArmaVersion As String = ConfigurationSettings.AppSettings("ArmaVersion").ToString


    Dim MODSLIST As String = ""

    Dim SettingsFile As String = strMainDirectory & "\ServerSettings2.xml"
    Dim UsersFile As String = strMainDirectory & "\Users.xml"

    Private Sub Empty(ByVal strUserName, ByVal strPassword)
        Try
            If VerifyUser(strUserName, strPassword) > 2 Then
                'Action Here

                LogGeneral("Log Me", strUserName)
            Else
                LogFailure("Log Me", strUserName)
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
        End Try
    End Sub

#Region "[  Web Exposed Functions  ]"

    <WebMethod(Description:="Verify Client and Server Version")> _
    Public Function VersionVerify() As String
        Try
            Return Version
        Catch ex As Exception
            Return ex.ToString
        End Try
    End Function

    <WebMethod(Description:="Get Arma Version")> _
Public Function ArmaVersion() As String
        Try
            Return strArmaVersion.ToUpper
        Catch ex As Exception
            Return ex.ToString
        End Try
    End Function

    <WebMethod(Description:="Get logs")> _
Public Function GetLogs(ByVal LogFileName As String) As String
        Try
            LogFileName = strMainDirectory & "\" & LogFileName
            Dim LogTempFile As String = strMainDirectory & "\LogTemp.txt"
            If File.Exists(LogFileName) Then
                File.Delete(LogTempFile)
                File.Copy(LogFileName, LogTempFile, True)

                Dim sr As New StreamReader(LogTempFile)
                Dim LastLines As String
                Try
                    sr.BaseStream.Seek(-3000, SeekOrigin.End)
                Catch ex As Exception

                End Try
                LastLines = sr.ReadToEnd
                Return LastLines
            Else
                Return "Log file not found"
            End If
            Return "No logs to return"
        Catch ex As Exception
            Return ex.ToString
        End Try
    End Function

    <WebMethod(Description:="Save Current config settings for server")> _
    Function SaveSettingsXML(ByVal strUserName As String, ByVal strPassword As String, ByVal SettingsXML As DataSet) As Boolean
        Try
            If VerifyUser(strUserName, strPassword) > 2 Then
                SettingsXML.WriteXml(SettingsFile)
                LogGeneral("Config Settings Changed", strUserName)
            Else
                LogFailure("Failed Settings Change attempt", strUserName)
            End If
            Return True
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
        End Try
    End Function

    <WebMethod(Description:="Get Current config settings for server")> _
    Function GetSettingsXML(ByVal strUserName As String, ByVal strPassword As String) As DataSet
        Try
            If VerifyUser(strUserName, strPassword) > 2 Then
                Dim dsSettings As New DataSet
                If File.Exists(SettingsFile) Then
                    dsSettings.ReadXml(SettingsFile)
                End If
                Return dsSettings
            End If
            Return Nothing
        Catch ex As Exception
            Dim returnTable As New DataTable
            returnTable.TableName = "ErrorTable"
            returnTable.Columns.Add("Error Message")
            returnTable.Columns.Add("Error String")
            Dim r As DataRow
            r = returnTable.NewRow
            r.Item(0) = ex.Message
            r.Item(1) = ex.ToString
            returnTable.Rows.Add(r)
            Dim dsSet As New DataSet
            dsSet.Tables.Add(returnTable)
            LogFailure(ex.Message, des.Decrypt(strUserName))
            Return dsSet
        End Try
    End Function

    <WebMethod(Description:="Show missions on server")> _
    Public Function ShowMissions(ByVal strUserName As String, ByVal strPassword As String) As String()
        Try
            If VerifyUser(strUserName, strPassword) > 2 Then
                'Action Here
                Dim ReturnMe As String() = {"No Missions Found"}
                If System.IO.Directory.Exists(strMissionDirectory) Then
                    Dim strFileList As String() = System.IO.Directory.GetFiles(strMissionDirectory)
                    Return strFileList
                    Exit Function
                End If
                'LogGeneral("Log Me", strUserName)
                Return ReturnMe
            Else
                LogFailure("Log Me", strUserName)
                Dim rStr As String() = {"Failure", "User Not Verified"}
                Return rStr
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Dim rStr As String() = {ex.Message, ex.ToString}
            Return rStr
        End Try
    End Function

    <WebMethod(Description:="Start new server instance")> _
    Public Function StartServer(ByVal strUserName, ByVal strPassword) As String
        Try
            If VerifyUser(strUserName, strPassword) > 1 Then
                'Action Here
                'See if any servers are running
                Dim p As Process
                For Each p In Process.GetProcesses
                    If p.ProcessName = Replace(strExeName, ".exe", "") Then
                        Return "Process currently running"
                    End If
                Next

                'write out a new config file
                Dim strConfigTemplate As String = My.Computer.FileSystem.ReadAllText(strMainDirectory & "\" & strTemplateFile)

                If File.Exists(strMainDirectory & "\" & strTemplateFile) = False Then
                    File.Copy("resources\" & strTemplateFile, strMainDirectory & "\" & strTemplateFile)
                End If

                Dim dsSettings As New DataSet
                If File.Exists(SettingsFile) Then
                    dsSettings.ReadXml(SettingsFile)
                End If

                Dim r As DataRow = dsSettings.Tables("ConfigSettings").Rows(0)
                Dim Password As String = r.Item("Password")
                Dim AdminPassword As String = r.Item("AdminPassword")
                'Dim Mode As String = r.Item("Mode")
                'Dim Mission As String = r.Item("Mission")
                'Dim Param1 As String = CInt(r.Item("Param1"))
                'Dim Param2 As String = CInt(r.Item("Param2"))
                Dim ServerName As String = r.Item("ServerName")
                Dim Persistent As Boolean = CBool(r.Item("Persistent"))
                Dim MaxPlayers As Integer = CInt(r.Item("MaxPlayers"))
                Dim MOTD As String = r.Item("MOTD")
                Dim MODS As String = r.Item("MODS")
                Dim Port As Integer = CInt(r.Item("PORT"))

                Dim MOTD_Split As String() = Split(MOTD, "|")
                Dim s As String
                MOTD = ""
                For Each s In MOTD_Split
                    s = """" & Trim(s) & """," & vbCrLf
                    MOTD = MOTD & s
                Next
                MOTD = Replace(MOTD, """", "")
                MOTD = Replace(MOTD, "[", "")
                MOTD = Replace(MOTD, "]", "")
                MOTD = Replace(MOTD, "'", "")


                If MODS <> "" Then MODSLIST = MODS

                strConfigTemplate = strConfigTemplate.Replace("[PASSWORD]", Password)
                strConfigTemplate = strConfigTemplate.Replace("[ADMINPASSWORD]", AdminPassword)
                strConfigTemplate = strConfigTemplate.Replace("[SERVERNAME]", ServerName)
                strConfigTemplate = strConfigTemplate.Replace("[MOTD]", MOTD)
                strConfigTemplate = strConfigTemplate.Replace("[MAXPLAYERS]", MaxPlayers)
                If Persistent = True Then
                    strConfigTemplate = strConfigTemplate.Replace("[PERSISTENT]", "1")
                Else
                    strConfigTemplate = strConfigTemplate.Replace("[PERSISTENT]", "0")
                End If

                'check if it is arma2
                Dim MissionOut As String = ""
                Select Case strArmaVersion.ToUpper
                    Case "ARMA"
                        'Build Mission Section
                        Dim MissionTemplate As String = "class Mission[COUNT]" & vbNewLine & _
                                "{" & vbNewLine & _
                                "   template=[MISSION];" & vbNewLine & _
                                "   param1=[PARAM1];" & vbNewLine & _
                                "   param2=[PARAM2];" & vbNewLine & _
                                "   cadetMode = [MODE];" & vbNewLine & _
                                "};" & vbNewLine

                        Dim dtMissions As DataTable = dsSettings.Tables("Missions")
                        Dim mI As Integer = 0
                        For Each r1 As DataRow In dtMissions.Rows
                            Dim s1 As String = MissionTemplate
                            s1 = s1.Replace("[COUNT]", mI)
                            s1 = s1.Replace("[MISSION]", r1.Item("Mission Name"))
                            s1 = s1.Replace("[PARAM1]", r1.Item("Param 1"))
                            s1 = s1.Replace("[PARAM2]", r1.Item("Param 2"))
                            If r1.Item("Difficulty") = "Veteran" Then
                                s1 = s1.Replace("[MODE]", "0")
                            Else
                                s1 = s1.Replace("[MODE]", "1")
                            End If
                            mI += 1
                            MissionOut += s1
                        Next
                    Case "ARMA2"
                        'Build Mission Section
                        Dim MissionTemplate As String = "class Mission[COUNT]" & vbNewLine & _
                                "{" & vbNewLine & _
                                "   template=[MISSION];" & vbNewLine & _
                                "   difficulty = [MODE];" & vbNewLine & _
                                "};" & vbNewLine

                        Dim dtMissions As DataTable = dsSettings.Tables("Missions")
                        Dim mI As Integer = 0
                        For Each r1 As DataRow In dtMissions.Rows
                            Dim s1 As String = MissionTemplate
                            s1 = s1.Replace("[COUNT]", mI)
                            s1 = s1.Replace("[MISSION]", r1.Item("Mission Name"))
                            s1 = s1.Replace("[PARAM1]", r1.Item("Param 1"))
                            s1 = s1.Replace("[PARAM2]", r1.Item("Param 2"))
                            s1 = s1.Replace("[MODE]", r1.Item("Difficulty").ToString.ToLower)
                            mI += 1
                            MissionOut += s1
                        Next
                End Select

                strConfigTemplate = strConfigTemplate.Replace("[MISSIONS]", MissionOut)

                My.Computer.FileSystem.WriteAllText(strMainDirectory & "\" & strConfigFile, strConfigTemplate, False)

                'start the server
                If MODSLIST <> "" Then
                    MODSLIST = "-mod=" & MODSLIST & " "
                End If

                Dim myProcess As Process = New Process

                'if it sees "beta" in the mods list, it changes the executable location to be the beta subfolder
                Dim strExecutable As String = strMainDirectory & "\" & strExeName
                Dim aMods As String() = Split(MODS, ";")
                For Each s1 As String In aMods
                    If s1.ToLower = "beta" Then
                        strExecutable = strMainDirectory & "\beta\" & strExeName
                    End If
                Next

                myProcess.StartInfo.FileName = strExecutable
                myProcess.StartInfo.Arguments = "-config=" & strConfigFile & " -profiles=" & strProfileLocation & " " & MODSLIST & " -name=" & strProfileName & " -nomap -port=" & Port
                myProcess.StartInfo.WorkingDirectory = strMainDirectory
                myProcess.StartInfo.UseShellExecute = True
                myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                myProcess.Start()
                LogGeneral("Server Started", strUserName)
                Return "Success"
            Else
                LogFailure("Failed Server Start Attempt. Invalid Credentials", strUserName)
                Return "Failed"
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Return ex.Message
        End Try
    End Function

    <WebMethod(Description:="Start new server instance")> _
    Public Function StartTSServer(ByVal strUserName, ByVal strPassword) As String
        Try
            If VerifyUser(strUserName, strPassword) > 1 Then
                'Action Here
                'See if any servers are running
                Dim p As Process
                For Each p In Process.GetProcesses
                    If p.ProcessName = Replace(strTSExeName, ".exe", "") Then
                        Return "Process currently running"
                    End If
                Next

                Dim myProcess As Process = New Process
                Dim strExecutable As String = strTSDirectory & "\" & strTSExeName & ".exe"
                myProcess.StartInfo.FileName = strExecutable
                myProcess.StartInfo.Arguments = ""
                myProcess.StartInfo.WorkingDirectory = strTSDirectory
                myProcess.StartInfo.UseShellExecute = True
                myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                myProcess.Start()
                LogGeneral("TS Server Started from " & strExecutable, strUserName)
                Return "Success"
            Else
                LogFailure("Failed TS Server Start Attempt. Invalid Credentials", strUserName)
                Return "Failed"
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Return ex.Message
        End Try
    End Function

    <WebMethod(Description:="Stop currently running server")> _
Public Function StopServer(ByVal strUserName, ByVal strPassword) As Boolean
        Try
            If VerifyUser(strUserName, strPassword) > 2 Then
                'Action Here
                Dim p As Process
                For Each p In Process.GetProcesses
                    If p.ProcessName = Replace(strExeName, ".exe", "") Then
                        p.Kill()
                        LogGeneral("Server Stopped", strUserName)
                        Return True
                    End If
                Next
                Return False
            Else
                LogFailure("Failed Server Stop. Invalid Credentials", strUserName)
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Return False
        End Try
    End Function

    <WebMethod(Description:="Stop currently running server")> _
Public Function StopTSServer(ByVal strUserName, ByVal strPassword) As Boolean
        Try
            If VerifyUser(strUserName, strPassword) > 2 Then
                'Action Here
                Dim p As Process
                For Each p In Process.GetProcesses
                    If p.ProcessName = strTSExeName Then
                        p.Kill()
                        LogGeneral("TS Server Stopped", strUserName)
                        Return True
                    End If
                Next
                Return False
            Else
                LogFailure("Failed TS Server Stop. Invalid Credentials", strUserName)
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Return False
        End Try
    End Function

    <WebMethod(Description:="Server Status Function")> _
    Public Function ServerStatus(ByVal strUserName, ByVal strPassword) As String()
        Dim aReturn As String() = {False, "Not Checked", ""}
        Try
            If VerifyUser(strUserName, strPassword) > -2 Then
                'Action Here
                Dim p As Process
                For Each p In Process.GetProcesses
                    'ReturnMe = p.ProcessName
                    If p.ProcessName = Replace(strExeName, ".exe", "") Then
                        aReturn(0) = True
                        Exit Try
                    End If
                    aReturn(2) += p.ProcessName & " || "
                Next
                aReturn(0) = False
                aReturn(1) = "Not Running"
            Else
                LogFailure("Failed Server Status Request. Invalid Credentials", strUserName)
                aReturn(0) = False
                aReturn(1) = "Invalid User"
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            aReturn(0) = False
            aReturn(1) = ex.Message
            aReturn(2) = ex.ToString
        End Try
        Return aReturn
    End Function

    <WebMethod(Description:="Server Status Function")> _
Public Function ServerTSStatus(ByVal strUserName, ByVal strPassword) As String()
        Dim aReturn As String() = {False, "Not Checked", ""}
        Try
            If VerifyUser(strUserName, strPassword) > -2 Then
                'Action Here
                Dim p As Process
                For Each p In Process.GetProcesses
                    'ReturnMe = p.ProcessName
                    If p.ProcessName = "ts3server_win32" Then
                        aReturn(0) = True
                        Exit Try
                    End If
                    aReturn(2) += p.ProcessName & " || "
                Next
                aReturn(0) = False
                aReturn(1) = "Not Running"
            Else
                LogFailure("Failed Server Status Request. Invalid Credentials", strUserName)
                aReturn(0) = False
                aReturn(1) = "Invalid User"
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            aReturn(0) = False
            aReturn(1) = ex.Message
            aReturn(2) = ex.ToString
        End Try
        Return aReturn
    End Function

    <WebMethod(Description:="Delete a Mission from the list")> _
    Public Function DeleteMission(ByVal strUserName As String, ByVal strPassword As String, ByVal MissionName As String) As Boolean
        Try
            If VerifyUser(strUserName, strPassword) > 2 Then
                'Action Here
                MissionName = strMissionDirectory & "\" & MissionName & ".pbo"
                If File.Exists(MissionName) Then
                    File.Delete(MissionName)
                    LogGeneral("Mission " & MissionName & " deleted.", strUserName)
                    Return True
                Else
                    LogGeneral("Mission " & MissionName & " deleted. File does not exist.", strUserName)
                    Return False
                End If
            Else
                LogFailure("Mission " & MissionName & " not deleted. Invalid Credentials.", strUserName)
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Return False
        End Try
    End Function

    <WebMethod(Description:="File Upload Webservice")> _
Public Function UploadFile(ByVal strUserName As String, ByVal strPassword As String, _
        ByVal strFileName As String, ByVal objFile As Byte(), ByRef strReturn As String) As String
        Try
            If VerifyUser(strUserName, strPassword) > 2 Then
                'Action Here
                Dim bolReturnStatus As Boolean = False

                Dim objFileStream As FileStream = Nothing

                'making sure the base directory string ends with a \ so that
                'the file is uploaded to the correct spot
                If strMissionDirectory.EndsWith("\") = False Then strMissionDirectory += "\"

                Try
                    ''simple username and password check nothing special. 
                    ''Should use something so that not just anyone is uploading file
                    ''(unless that is what you want)
                    'If Not strUserName = "username" AndAlso Not strPassword = "password" Then
                    '    Throw New UnauthorizedAccessException
                    'End If


                    'checks to make sure the base directory exists
                    'if not it attempts to create it
                    If checkfolderexists(strMissionDirectory) = False Then
                        Throw New Exception("Base Folder does not exist and could not create.")
                    End If

                    'creates the file by opening and setting the fileaccess to write
                    objFileStream = File.Open(strMissionDirectory & strFileName, FileMode.Create, FileAccess.Write)

                    'byte count
                    Dim lngLen As Long = objFile.Length

                    'Write the file
                    objFileStream.Write(objFile, 0, CType(lngLen, Integer))

                    'clears the buffer and writes any buffered data
                    objFileStream.Flush()

                    'close the file so it can be access by other files
                    objFileStream.Close()

                    'return a successful upload status
                    bolReturnStatus = True

                    'Cleanup Mission Names
                    Dim Filename As String = Replace(strFileName, "_", " ")
                    File.Move(strMissionDirectory & strFileName, strMissionDirectory & Filename)

                Catch exc As Exception
                    'catchall error handler
                    LogFailure(exc.ToString, strUserName)
                    strReturn = "Exception Occurred. Error: " & exc.Message.ToString

                Finally

                    'cleanup just in case
                    If Not objFileStream Is Nothing Then
                        objFileStream.Close()
                    End If

                End Try
                LogGeneral("New mission " & strFileName & " uploaded.", strUserName)
                Return bolReturnStatus
            Else
                LogFailure("Attempted file upload canceled. Unauthorized.", strUserName)
                Return False
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Return ex.ToString
        End Try
    End Function
#End Region

#Region "[  User Web Functions  ]"
    <WebMethod(Description:="Check User Administrative Level")> _
 Public Function CheckUser(ByVal strUserName As String, ByVal strPassword As String) As Integer
        Dim Level As Integer = VerifyUser(strUserName, strPassword)
        Dim Success As String = "Failed "
        If Level > -2 Then Success = "Successful "
        LogGeneral(Success & "User Login Attempt", strUserName)
        Return Level
    End Function

    <WebMethod(Description:="Get Users List")> _
Public Function GetUsers(ByVal strUserName As String, ByVal strPassword As String) As DataTable
        Try
            If VerifyUser(strUserName, strPassword) > 3 Then
                FileDecrypt(UsersFile)
                Dim dsSet As New DataSet
                dsSet.ReadXml(UsersFile)
                Dim dtTable As DataTable = dsSet.Tables(0)
                FileEncrypt(UsersFile)
                Return dtTable
            End If
            LogFailure("Failed user list attempt. Unauthorized.", strUserName)
            Return Nothing
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Return Nothing
        End Try
    End Function

    <WebMethod(Description:="Modify User")> _
Public Function ModifyUser(ByVal strUserName As String, ByVal strPassword As String, ByVal userFunction As String, _
         ByVal userUsername As String, ByVal userPassword As String, ByVal userAdminLevel As String, _
         ByVal userStartDate As String, ByVal userStopDate As String) As String
        Try
            userFunction = des.Decrypt(userFunction)
            userUsername = des.Decrypt(userUsername)
            userPassword = des.Decrypt(userPassword)
            userAdminLevel = des.Decrypt(userAdminLevel)
            userStartDate = des.Decrypt(userStartDate)
            userStopDate = des.Decrypt(userStopDate)

            If VerifyUser(strUserName, strPassword) > 3 Then
                If File.Exists(UsersFile) Then
                    FileDecrypt(UsersFile)
                    'if it exists, import it and add to it
                    Dim dsSet As New DataSet
                    dsSet.ReadXml(UsersFile)
                    Dim dtTable As DataTable = dsSet.Tables(0)
                    FileEncrypt(UsersFile)

                    Select Case userFunction
                        Case "AddUser"
                            'see if a user already exists with that name
                            For Each eR As DataRow In dtTable.Rows
                                If eR.Item("username") = userUsername Then
                                    Return "User already exists. Add User aborted"
                                End If
                            Next

                            'see if the dates are valid
                            If IsDate(userStartDate) = False Or IsDate(userStopDate) = False Then
                                Return "Date not valid. User Add aborted"
                            End If

                            If CDate(userStartDate) > CDate(userStopDate) Then
                                Return "Start Date must be BEFORE Stop Date"
                            End If

                            'add the user
                            Dim r As DataRow = dtTable.NewRow
                            r.Item("username") = userUsername
                            r.Item("password") = userPassword
                            r.Item("adminlevel") = userAdminLevel
                            r.Item("startdate") = userStartDate
                            r.Item("stopdate") = userStopDate
                            dtTable.Rows.Add(r)
                            dtTable.WriteXml(UsersFile)
                            FileEncrypt(UsersFile)
                            LogGeneral("User " & userUsername & " added.", strUserName)
                            Return "User Added"
                        Case "EditUser"
                            'find the user
                            For Each r As DataRow In dtTable.Rows
                                'when it matches, change the info
                                If r.Item("username") = userUsername Then
                                    If userPassword <> "$//NONE\\$" Then
                                        r.Item("password") = userPassword
                                    End If
                                    r.Item("adminlevel") = userAdminLevel
                                    r.Item("startdate") = userStartDate
                                    r.Item("stopdate") = userStopDate
                                    r.AcceptChanges()
                                End If
                            Next
                            dtTable.WriteXml(UsersFile)
                            FileEncrypt(UsersFile)
                            LogGeneral("User " & userUsername & " edited.", strUserName)
                            Return "User Modifed"
                        Case "DeleteUser"
                            Dim i As Integer = 0
                            While i < dtTable.Rows.Count
                                If dtTable.Rows(i).Item("username").ToString = userUsername Then
                                    dtTable.Rows(i).Delete()
                                End If
                                i += 1
                            End While
                            dtTable.AcceptChanges()
                            dtTable.WriteXml(UsersFile)
                            FileEncrypt(UsersFile)
                            LogGeneral("User " & userUsername & " deleted.", strUserName)
                            Return "User " & userUsername & " Deleted"
                    End Select
                End If
            ElseIf VerifyUser(strUserName, strPassword) = -1 And File.Exists(UsersFile) = False Then
                If userFunction = "AddUser" Then
                    If userUsername <> Nothing And userPassword <> Nothing And userAdminLevel <> Nothing And userStartDate <> Nothing And userStopDate <> Nothing Then
                        'create the sctructure and save the user
                        Dim dtTable As New DataTable
                        dtTable.TableName = "Users"
                        dtTable.Columns.Add("username")
                        dtTable.Columns.Add("password")
                        dtTable.Columns.Add("adminlevel")
                        dtTable.Columns.Add("startdate")
                        dtTable.Columns.Add("stopdate")

                        Dim r As DataRow = dtTable.NewRow
                        r.Item("username") = userUsername
                        r.Item("password") = userPassword
                        r.Item("adminlevel") = userAdminLevel
                        r.Item("startdate") = userStartDate
                        r.Item("stopdate") = userStopDate
                        dtTable.Rows.Add(r)

                        dtTable.WriteXml(UsersFile)
                        FileEncrypt(UsersFile)
                        LogGeneral("User " & userUsername & " added.", strUserName)
                        Return "User Added"
                    End If
                End If
            End If
            Return Nothing
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Return ex.ToString
        End Try
    End Function
#End Region

#Region "[  Ban List Functions  ]"

    <WebMethod(Description:="Get Ban List")> _
    Public Function BanGetList(ByVal strUserName, ByVal strPassword) As String
        Try
            If File.Exists(strMainDirectory & "\ban.txt") = False Then
                File.CreateText(strMainDirectory & "\ban.txt")
            End If
            If VerifyUser(strUserName, strPassword) > 2 Then
                'Action Here
                Dim List As String = Replace(My.Computer.FileSystem.ReadAllText(strMainDirectory & "\ban.txt"), vbCrLf, "||")
                Return List
            Else
                LogFailure("Failed User Ban listing. User unauthorized.", strUserName)
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
        End Try
        Return Nothing
    End Function

    <WebMethod(Description:="Add User to Ban List")> _
    Public Function BanAddUser(ByVal strUserName, ByVal strPassword, ByVal UserName) As String
        Try
            If VerifyUser(strUserName, strPassword) > 2 Then
                If File.Exists(strMainDirectory & "\ban.txt") = False Then
                    File.CreateText(strMainDirectory & "\ban.txt")
                End If
                'Action Here
                Dim builder As New System.Text.StringBuilder
                Dim fileName As String = strMainDirectory & "\ban.txt"

                ' Read the file line by line
                Using reader As New IO.StreamReader(fileName)
                    While Not reader.EndOfStream()
                        Dim input As String = reader.ReadLine()

                        ' If the text <> server name fill the StringBuilder
                        If input <> UserName Then
                            builder.AppendLine(input)
                        End If

                    End While
                End Using

                builder.AppendLine(UserName)

                ' Write the file to disk
                Dim writer As New IO.StreamWriter(fileName)
                writer.Write(builder.ToString)
                writer.Close()
                LogGeneral("User " & UserName & " banned", strUserName)
                Return "User " & UserName & " banned"
            Else
                LogFailure("Failed Add Ban. Unauthorized.", strUserName)
                Return Nothing
            End If
        Catch ex As Exception
            LogFailure(ex.ToString, strUserName)
            Return ex.Message
        End Try
    End Function

    <WebMethod(Description:="Remove User from Ban List")> _
    Public Function BanRemoveUser(ByVal strUserName, ByVal strPassword, ByVal UserName) As String

        Dim builder As New System.Text.StringBuilder
        Dim fileName As String = strMainDirectory & "\ban.txt"

        ' Read the file line by line
        Using reader As New IO.StreamReader(fileName)
            While Not reader.EndOfStream()
                Dim input As String = reader.ReadLine()

                ' If the text <> server name fill the StringBuilder
                If input <> UserName Then
                    builder.AppendLine(input)
                End If

            End While
        End Using

        ' Write the file to disk
        Dim writer As New IO.StreamWriter(fileName)
        writer.Write(builder.ToString)
        writer.Close()
        Return "User " & UserName & " unbanned"

    End Function
#End Region

#Region "[  Private Functions  ]"
    Private Function VerifyUser(ByVal UserName As String, ByVal Password As String) As Integer
        Try
            UserName = des.Decrypt(UserName)
            'See if a user settings file exists
            If File.Exists(UsersFile) = False And (UserName = "tempadministrator" And des.Decrypt(Password) = "password") Then
                Return -1
            Else
                'data kept in users xml (all encrpyted)
                '  username
                '  password
                '  admin level
                '  start date
                '  end date
                If File.Exists(UsersFile) Then
                    'decrypt, move xml data to datatable, encrypt file
                    FileDecrypt(UsersFile)
                    Dim dsSet As New DataSet
                    dsSet.ReadXml(UsersFile)
                    Dim dtTable As DataTable = dsSet.Tables(0)
                    Dim fE As String = FileEncrypt(UsersFile)
                    If Left(fE, 3) = "ERR" Then
                        Return fE
                    End If

                    'if it exists, check user and password against it

                    For Each r As DataRow In dtTable.Rows
                        If r.Item("username") = UserName And r.Item("password") = des.Decrypt(Password) Then
                            If Now > CDate(r.Item("startdate")) And Now < CDate(r.Item("stopdate")) Then
                                Return Mid(r.Item("adminlevel"), 7, 1)
                            End If
                        End If
                    Next
                End If

                Return -2
            End If
        Catch ex As Exception
            My.Computer.FileSystem.WriteAllText(strMainDirectory & "\error.txt", ex.ToString, False)
            Return -3
        End Try
    End Function

    Function checkfolderexists(ByVal sFolder As String) As Boolean

        'split the directory out so that you can do a check for each folder
        Dim sFolderSplit() As String = sFolder.Split("\")

        Dim strFolder As String = ""          'current folder to check              
        Try
            'loop through each folder
            For x As Int16 = 0 To sFolderSplit.GetUpperBound(0) - 1
                'set the current folder
                strFolder += sFolderSplit(x) & "\"

                'do check
                If Directory.Exists(strFolder) = False Then
                    'try to create the none existing folder
                    Directory.CreateDirectory(strFolder)
                End If
            Next

            'looped through all folders successfully
            Return True
        Catch ex As Exception
            'error occured
            Return False
        End Try

    End Function

    Private Function FileEncrypt(ByVal FileName As String) As String
        Try
            If File.Exists(FileName) Then
                Dim strContents = My.Computer.FileSystem.ReadAllText(FileName)
                strContents = des.Encrypt(strContents)
                My.Computer.FileSystem.WriteAllText(FileName, strContents, False)
                Return "Done"
            End If
            Return "ERR: File Does Not Exist"
        Catch ex As Exception
            Return "ERR: " & ex.Message
        End Try
        Return Nothing
    End Function

    Private Function FileDecrypt(ByVal FileName As String) As String
        Try
            If File.Exists(FileName) Then
                Dim strContents = My.Computer.FileSystem.ReadAllText(FileName)
                strContents = des.Decrypt(strContents)
                My.Computer.FileSystem.WriteAllText(FileName, strContents, False)
                Return "Done"
            End If
            Return "ERR: File Does Not Exist"
        Catch ex As Exception
            Return "ERR: " & ex.Message
        End Try
        Return Nothing
    End Function
#End Region

#Region "[  Logging Functions  ]"
    Public Sub LogGeneral(ByVal Message As String, Optional ByRef Username As String = "No User", Optional ByVal FileName As String = "$//NONE\\$")
        If Username <> "No User" Then
            Username = des.Decrypt(Username)
        End If
        If FileName = "$//NONE\\$" Then FileName = strMainDirectory & "\ManagerLog.txt"
        Dim ClientIP As String = HttpContext.Current.Request.UserHostAddress
        Dim exists As Boolean = False
        If System.IO.File.Exists(FileName) Then exists = True
        Dim objWriter As New System.IO.StreamWriter(FileName, exists)
        Dim LogLine As String = "General /// " & Now.ToString & " /// " & ClientIP & " /// " & Username & "/// " & Message
        objWriter.WriteLine(LogLine)
        objWriter.Close()
    End Sub

    Public Sub LogFailure(ByVal Message As String, Optional ByRef Username As String = "No User", Optional ByVal FileName As String = "$//NONE\\$")
        If Username <> "No User" Then
            Username = des.Decrypt(Username)
        End If
        If FileName = "$//NONE\\$" Then FileName = strMainDirectory & "\ManagerLog.txt"
        Dim ClientIP As String = HttpContext.Current.Request.UserHostAddress
        Dim exists As Boolean = False
        If System.IO.File.Exists(FileName) Then exists = True
        Dim objWriter As New System.IO.StreamWriter(FileName, exists)
        Dim LogLine As String = "Failure /// " & Now.ToString & " /// " & ClientIP & " /// " & Username & "/// " & Message
        objWriter.WriteLine(LogLine)
        objWriter.Close()
    End Sub
#End Region

#Region "[  Mumble Server Functions  ]"
    <WebMethod(Description:="Murmur Functions")> _
    Public Function MurmurFunction(ByVal strUserName, ByVal strPassword, ByVal MurmurString) As String

        Dim ReturnMe As String = ""
        If VerifyUser(strUserName, strPassword) > 2 Then



        End If


        Return ReturnMe

    End Function
#End Region
End Class